package com.fcg.redis.refresh.bean;

import com.fcg.redis.refresh.annotation.RefreshCache;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 扫描所有bean,记录带有RefreshCache注解的方法,并执行一次
 *
 * @author FCG
 * @see RefreshCache
 */
@Component
public class RefreshCacheBeanProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        List<CacheInvoker> invokers = Stream.of(methods)
                .filter(method -> method.isAnnotationPresent(RefreshCache.class))
                .map(method -> {
                    CacheInvoker invoker = new CacheInvoker(bean, method);
                    invoker.doInvoke();
                    return invoker;
                })
                .collect(Collectors.toList());
        CacheInvoker.addInvokers(invokers);
        return bean;
    }
}
